package com.zhuiyun.project.api.vipPlan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhuiyun.project.api.coachmanagement.model.MemberPlanActionModel;
import com.zhuiyun.project.api.memberUserManagement.entity.MemberUserManagement;
import com.zhuiyun.project.api.memberUserManagement.mapper.MemberUserManagementMapper;
import com.zhuiyun.project.api.plan.fitnessAction.entity.FitnessAction;
import com.zhuiyun.project.api.plan.fitnessPlan.entity.FitnessPlan;
import com.zhuiyun.project.api.plan.fitnessPlanAction.entity.FitnessPlanAction;
import com.zhuiyun.project.api.plan.fitnessPlanActionCount.entity.FitnessPlanActionCount;
import com.zhuiyun.project.api.plan.fitnessSeries.entity.FitnessSeries;
import com.zhuiyun.project.api.plan.fitnessType.entity.FitnessType;
import com.zhuiyun.project.api.reservation.entity.Reservation;
import com.zhuiyun.project.api.reservation.mapper.ReservationMapper;
import com.zhuiyun.project.api.userrecord.entity.UserRecord;
import com.zhuiyun.project.api.userrecord.mapper.UserRecordMapper;
import com.zhuiyun.project.api.userrecord.model.BodyFatModel;
import com.zhuiyun.project.api.userrecord.model.UploadUserRecordModel;
import com.zhuiyun.project.api.vipPlan.entity.ActionCount;
import com.zhuiyun.project.api.vipPlan.entity.MemberPlan;
import com.zhuiyun.project.api.vipPlan.entity.MemberPlanAction;
import com.zhuiyun.project.api.vipPlan.entity.MemberSeries;
import com.zhuiyun.project.api.vipPlan.mapper.ActionCountMapper;
import com.zhuiyun.project.api.vipPlan.mapper.MemberPlanActionMapper;
import com.zhuiyun.project.api.vipPlan.mapper.MemberSeriesMapper;
import com.zhuiyun.project.api.vipPlan.mapper.VipPlanMapper;
import com.zhuiyun.project.api.vipPlan.model.*;
import com.zhuiyun.project.api.vipPlan.service.VipPlanService;
import com.zhuiyun.project.common.errorCode.CommonException;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.utils.BeanUtils;
import com.zhuiyun.project.utils.bodyFatPercentageUtils;
import com.zhuiyun.project.utils.validator.ValidatorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;

/**
 * @ClassName VipPlanServiceImpl
 * @Description TODO 会员课程业务逻辑层实现类
 * @Author 杨友朋
 * @Date 2023/12/4 15:45
 **/
@Service
public class VipPlanServiceImpl implements VipPlanService {
    @Autowired
    VipPlanMapper vipPlanMapper;

    @Autowired
    ActionCountMapper actionCountMapper;

    @Autowired
    MemberUserManagementMapper memberUserManagementMapper;

    @Autowired
    MemberSeriesMapper memberSeriesMapper;

    @Autowired
    ReservationMapper reservationMapper;

    @Autowired
    MemberPlanActionMapper memberPlanActionMapper;
    @Autowired
    UserRecordMapper userRecordMapper;

    @Override
    public CommonResult selectPlan(int coachId) {
        // 教验参数是否合法
        if(coachId<1){
            return CommonResult.error("参数校验失败");
        }
        // 查询数据库
        List<FitnessPlan> fitnessSeries = vipPlanMapper.selectPlan(coachId);
        if(fitnessSeries==null){
            return CommonResult.error("查询训练动作失败");
        }
        // 判断是否存在数据
        if(fitnessSeries.size()<1){
            return CommonResult.error("查询失败");
        }
        return CommonResult.ok(fitnessSeries);
    }

    @Override
    @Transactional
    public CommonResult memberAddPlan(AddPlanModel addPlanModel) {
        // 教验参数是否合法
        if(addPlanModel.getSeriesId()==0){
            return CommonResult.error("参数校验失败");
        }
        // 校验参数是否合法
        if(addPlanModel.getMemberId()==0){
            return CommonResult.error("参数校验失败");
        }
        // 创建用户、课程系列关联实体对象
        MemberSeries memberSeries=new MemberSeries();
        // 模型对象赋值给实体对象
        BeanUtils.copy(addPlanModel,memberSeries);
        // 添加至数据库
        int i=memberSeriesMapper.insertSeries(memberSeries);
        if(i>0==false){
            return CommonResult.error("操作失败");
        }
        // 根据计划id查询计划下的课程
        List<FitnessPlan> fitnessPlans=vipPlanMapper.selectPlan(addPlanModel.getSeriesId());
        if(fitnessPlans==null){
            return CommonResult.error("查询训练动作失败");
        }
        // 遍历查到每个课程
        for (int i1=0;i1<fitnessPlans.size();i1++){
            // planId
            Integer planId = fitnessPlans.get(i1).getId();
            // seriesId
            Integer seriesId = memberSeries.getId();
            // memberId
            Integer memberId = memberSeries.getMemberId();
            MemberPlan memberPlan=new MemberPlan();
            // 课程id
            memberPlan.setPlanId(planId);
            // 用户ID
            memberPlan.setMemberId(memberId);
            // 系列id
            memberPlan.setSeriesId(seriesId);
            // 添加至数据库
            int i3 = vipPlanMapper.insertPlan(memberPlan);
            if(i3>0==false){
                return CommonResult.error("操作失败");
            }
            // 创建预约实体对象
            Reservation reservation=new Reservation();
            // 预约状态
            reservation.setReservationStatus("0");
            // 预约课程id
            reservation.setCourseId(memberPlan.getId());
            // 预约人id
            reservation.setStudentId(memberId);
            // 教练id
            reservation.setCoachId(fitnessPlans.get(i1).getCoachId());
            // 创建时间
            reservation.setCreateTime(new Date());
            // 修改时间
            reservation.setUpdateTime(new Date());
            // 添加至数据库
            int insert1 = reservationMapper.insert(reservation);
            if(insert1>0==false){
                return CommonResult.error("操作失败");
            }
            // 查询plan下的动作
            List<FitnessPlanAction> fitnessPlanActions = vipPlanMapper.selectAction(fitnessPlans.get(i1).getId());
            if(fitnessPlanActions==null){
                return CommonResult.error("查询训练动作失败");
            }
            // 遍历动作
            for(int i2=0;i2<fitnessPlanActions.size();i2++){
                // actionId
                Integer actionId = fitnessPlanActions.get(i2).getFitnessActionId();
                // 创建用户课程实体对象
                MemberPlanAction memberPlanAction=new MemberPlanAction();
                memberPlanAction.setPlanId(memberPlan.getId());
                memberPlanAction.setActionId(actionId);
                int i5 = memberPlanActionMapper.insertAction(memberPlanAction);
                if(i5>0==false){
                    return CommonResult.error("操作失败");
                }
                // 根据动作id查询动作信息对象
                List<FitnessPlanActionCount> fitnessPlanActionCount = vipPlanMapper.selectActionCount(fitnessPlanActions.get(i2).getId());
                if(fitnessPlanActionCount==null){
                    return CommonResult.error("查询动作失败");
                }
                for (int i4=0;i4<fitnessPlanActionCount.size();i4++){
                    // 创建动作统计对象
                    ActionCount actionCount=new ActionCount();
                    // 课程动作id
                    actionCount.setPlanActionId(memberPlanAction.getId());
                    // 场馆唯一标志
                    actionCount.setVenueUniqueIdentifier(fitnessPlanActionCount.get(i4).getVenueUniqueIdentifier());
                    // 器材id
                    actionCount.setEquipmentId(fitnessPlanActionCount.get(i4).getEquipmentId());
                    // 器材重量
                    actionCount.setEquipmentWeight(fitnessPlanActionCount.get(i4).getEquipmentWeight());
                    // 每组次数
                    actionCount.setActionCount(fitnessPlanActionCount.get(i4).getActionCount());
                    // 创建时间
                    actionCount.setCreateTime(new Date());
                    // 修改时间
                    actionCount.setUpdateTime(new Date());
                    // 添加至数据库
                    int insert = actionCountMapper.insert(actionCount);
                    if(insert>0==false){
                        return CommonResult.error("操作失败");
                    }
                }

            }
        }
        // 创建用户实体对象
        MemberUserManagement memberUserManagement=new MemberUserManagement();
        // id
        memberUserManagement.setId(addPlanModel.getMemberId());
        // 已分配标识
        memberUserManagement.setIsAllocation("0");
        // 修改时间
        memberUserManagement.setUpdateTime(new Date());
        // 执行数据库修改操作
        int ii = memberUserManagementMapper.updateById(memberUserManagement);
        // 判断操作是否成功
        if(ii>0){
            return CommonResult.ok("操作成功");
        }
        return CommonResult.error("操作失败");
    }

    /**
     * @param memberId
     * @param coachCode
     * @Author 杨友朋
     * @Description 学员查询训练动作
     * @Date 2023/12/4 20:33
     * @Return CommonResult
     */
    @Override
    public CommonResult selectAction(int memberId, String isComplete, String coachCode) {
        // 校验参数合法性
        if(memberId>0==false){
            return CommonResult.error("参数校验失败");
        }
        // 查询数据库
        List<ActionListModel> actionListModels=vipPlanMapper.memberSelectReservation(memberId,isComplete,coachCode);
        for (int i = 0; i < actionListModels.size(); i++) {
            ActionListModel actionListModel = actionListModels.get(i);
            List<MemberPlanActionModel> memberPlanActionModels = vipPlanMapper.selectActionByPlan(actionListModel.getId());
            actionListModel.setListDate(memberPlanActionModels);
        }
        // 判断是否存在数据
        if(actionListModels==null){
            return CommonResult.error("查询失败");
        }
        if(actionListModels.size()<1){
            return CommonResult.error("暂无数据");
        }
        return CommonResult.ok(actionListModels);
    }

    /**
     * @Author 杨友朋
     * @Description 查询时间
     * @Date 2023/12/6 9:44
     * @Return CommonResult
     * @param coachId
     */
    @Override
    public CommonResult selectSeries(int coachId,String venueUniqueIdentifier) {
        // 校验参数合法性
        if(coachId>0==false){
            return CommonResult.error("参数校验失败");
        }
        // 查询数据库
        List<FitnessSeries> fitnessSeries = vipPlanMapper.selectSeries(coachId,venueUniqueIdentifier);
        // 判断是否存在数据
        if(fitnessSeries==null){
            return CommonResult.error("查询失败");
        }
        if(fitnessSeries.size()<1){
            return CommonResult.error("暂无数据");
        }
        return CommonResult.ok(fitnessSeries);
    }

    /**
     * @Author 杨友朋
     * @Description 查询时间
     * @Date 2023/12/6 9:44
     * @Return CommonResult
     * @param coachId,reservationTime
     */
    @Override
    public CommonResult selectReservationTime(int coachId,String reservationTime) {
        // 校验参数合法性
        if(coachId>0==false){
            return CommonResult.error("参数校验失败");
        }
        if(reservationTime.equals("")||reservationTime==null){
            return CommonResult.error("参数校验失败");
        }
        // 查询数据库
        List<ReservationTimeModel> reservationTimeModels = vipPlanMapper.selectReservationTime(coachId, reservationTime);
        // 判断查询数据
        if(reservationTimeModels==null){
            return CommonResult.error("查询失败");
        }
        if(reservationTimeModels.size()<1){
            return CommonResult.error("暂无数据");
        }
        return CommonResult.ok(reservationTimeModels);
    }

    @Override
    public CommonResult reservationPlan(ReservationPlanModel reservationPlanModel) throws CommonException {
        // 模型类参数校验
        if(ValidatorUtil.ValidationObject(reservationPlanModel)){
            // 创建预约对象
            Reservation reservation=new Reservation();
            // 模型类copy至实体对象
            BeanUtils.copy(reservationPlanModel,reservation);
            // 修改时间
            reservation.setUpdateTime(new Date());
            // 预约状态
            reservation.setReservationStatus("1");
            // 操作数据库
            int i = vipPlanMapper.reservationPlan(reservation);
            if(i>0){
                return CommonResult.ok("操作成功");
            }
            return CommonResult.error("操作失败");
        }
        return CommonResult.error("参数校验失败");
    }

    /**
     * @Author 杨友朋
     * @Description
     * @Date 2023/12/7 10:21
     * @Return CommonResult
     * @param invitationCode,selectYear
     */
    @Override
    public CommonResult selectAllPlan(String invitationCode, String selectYear,String isComplete,String selectMonth,String daiXunLianDate) {
        // 查询数据库
        List<ActionListModel> actionListModels = vipPlanMapper.selectAllPlan(invitationCode, selectYear,isComplete,selectMonth,daiXunLianDate);
        // 判断是否查询成功
        if(actionListModels==null){
            return CommonResult.error("查询失败");
        }
        if(actionListModels.size()<1){
            return CommonResult.error("暂无数据");
        }
        return CommonResult.ok(actionListModels);
    }

    @Override
    public CommonResult selectActionByPlan(int planId) {
        if(planId==0){
            return CommonResult.error("参数校验失败");
        }
        List<MemberPlanActionModel> memberPlanActionModels = vipPlanMapper.selectActionByPlan(planId);
        // 判断是否查询成功
        if(memberPlanActionModels==null){
            return CommonResult.error("查询失败");
        }
        if(memberPlanActionModels.size()<1){
            return CommonResult.error("暂无数据");
        }
        for (int a=0;a<memberPlanActionModels.size();a++){
            List<ActionCount> actionCounts = vipPlanMapper.selectActionCountByActionId(memberPlanActionModels.get(a).getId());
            if(actionCounts==null){
                return CommonResult.error("查询失败");
            }
            memberPlanActionModels.get(a).setActionCounts(actionCounts);
            memberPlanActionModels.get(a).setCountAction(actionCounts.size());
        }
        return CommonResult.ok(memberPlanActionModels);
    }

    @Override
    public CommonResult selectActionByActionId(int actionId) {
        if (actionId>0==false){
            return CommonResult.error("参数校验失败");
        }
        List<ActionCount> actionCounts = vipPlanMapper.selectActionCountByActionId(actionId);
        return CommonResult.ok(actionCounts);
    }

    @Override
    public CommonResult removeActionCount(int actionId) {
        if (actionId>0==false){
            return CommonResult.error("参数校验失败");
        }
        int i = vipPlanMapper.removeActionCount(actionId);
        if(i>0){
            return CommonResult.ok("操作成功");
        }
        return CommonResult.error("操作失败");
    }

    @Override
    public CommonResult insertActionCount(ActionCountModel actionCountModel) {
        ActionCount actionCount=new ActionCount();
        BeanUtils.copy(actionCountModel,actionCount);
        int insert = actionCountMapper.insert(actionCount);
        if(insert>0){
            return CommonResult.ok("操作成功");
        }
        return CommonResult.error("操作失败");
    }

    @Override
    public CommonResult updateActionCount(ActionCountModel actionCountModel) {
        ActionCount actionCount=new ActionCount();
        BeanUtils.copy(actionCountModel,actionCount);
        int insert = actionCountMapper.updateById(actionCount);
        if(insert>0){
            return CommonResult.ok("操作成功");
        }
        return CommonResult.error("操作失败");
    }

    @Override
    public CommonResult removeAction(int actionId) {
        if (actionId>0==false){
            return CommonResult.error("参数校验失败");
        }
        int i = vipPlanMapper.removeAction(actionId);
        if(i>0){
            return CommonResult.ok("操作成功");
        }
        return CommonResult.error("操作失败");
    }

    @Override
    public CommonResult getFitnessType(int fitnessPurposeId) {
        if(fitnessPurposeId<1){
            return CommonResult.error("参数校验失败");
        }
        List<FitnessType> fitnessTypes=vipPlanMapper.getFitnessType(fitnessPurposeId);
        return CommonResult.ok(fitnessTypes);
    }

    @Override
    public CommonResult getAllAction(int fitnessTypeId) {
        if(fitnessTypeId<1){
            return CommonResult.error("参数校验失败");
        }
        List<FitnessAction> fitnessActions = vipPlanMapper.getAllAction(fitnessTypeId);
        return CommonResult.ok(fitnessActions);
    }

    @Override
    public CommonResult insertAction(InsertPlanActionModel planActionModel) {
        MemberPlanAction actionCount=new MemberPlanAction();
        BeanUtils.copy(planActionModel,actionCount);
        int insert = memberPlanActionMapper.insert(actionCount);
        if(insert>0){
            return CommonResult.ok("操作成功");
        }
        return CommonResult.error("操作失败");
    }

    @Override
    public CommonResult selectReservationById(int courseId) {
        ActionListModel actionListModel = vipPlanMapper.selectReservationById(courseId);
        if(actionListModel!=null){
            return CommonResult.ok(actionListModel);
        }
        return CommonResult.error("操作失败");
    }

    @Override
    public CommonResult cancelReservation(int courseId, int studentId) {
        int a=vipPlanMapper.cancelReservation(courseId,studentId);
        if(a>0){
            return CommonResult.ok("操作成功");
        }
        return CommonResult.error("操作失败");
    }

    @Override
    public CommonResult completePlan(AddPlanModel addPlanModel) {
        MemberPlan memberPlan=new MemberPlan();
        memberPlan.setId(addPlanModel.getPlanId());
        int a=vipPlanMapper.completePlan(memberPlan);
        if(a>0){
            Integer integer = vipPlanMapper.completeReservation(memberPlan);
            UserRecord userRecord = new UserRecord();
            userRecord.setMemberUserId(addPlanModel.getMemberUserId());
            userRecord.setRecordId(addPlanModel.getRecordId());
            Integer userr = vipPlanMapper.upNumber(userRecord);
            if (userr==0){  //如果是新学员还没有案例记录就添加他的记录
                vipPlanMapper.addUserRecord(userRecord);
            }
            if (integer > 0){
//                Body(addPlanModel);
                return CommonResult.ok("成功");
            }else {
                CommonResult.error("失败");
            }
            return CommonResult.ok("操作成功");
        }
        return CommonResult.error("操作失败");
    }
    /*
    * @Author wuwan
    * @Description 上传记录
    * @Date 2023/12/20 15:54
    * @Return
    */
    @Override
    public CommonResult upCompletePlan(AddPlanModel addPlanModel) {
            MemberPlan memberPlan=new MemberPlan();
            memberPlan.setId(addPlanModel.getPlanId());
            Integer integer = vipPlanMapper.upCompleteReservation(memberPlan);
            if (integer > 0){
                Body(addPlanModel);
                return CommonResult.ok("成功");
            }else {
                CommonResult.error("失败");
            }
        return CommonResult.error("操作失败");
    }
    /*
    * @Author wuwan
    * @Description 上传图片到案例表
    * @Date 2023/12/12 10:18
    * @Return
    */
    @Override
    public CommonResult saveImageToDatabase(AddImageCaseModel addImageCaseModel) {
        Integer integer = vipPlanMapper.saveImageToDatabase(addImageCaseModel);
        if (integer >= 1){
            return CommonResult.ok("操作成功");
        }
        return CommonResult.error("操作失败");
    }

    @Override
    public CommonResult DeleteImageToDatabase(AddImageCaseModel addImageCaseModel) {
        Integer integer = vipPlanMapper.DeleteImageToDatabase(addImageCaseModel);
        if (integer >= 1){
            return CommonResult.ok("操作成功");
        }
        return CommonResult.error("操作失败");
    }
    public void Body(AddPlanModel addPlanModel) {
        UserRecord userRecord1 = userRecordMapper.selectByUser(addPlanModel.getMemberUserId(), addPlanModel.getRecordId());
        // 判断是否记录过此用户
        if (userRecord1 == null) {
            UserRecord userRecord = new UserRecord();
            userRecord.setMemberUserId(addPlanModel.getMemberUserId());
            userRecord.setRecordId(addPlanModel.getRecordId());
            userRecord.setVenueUniqueIdentifier(addPlanModel.getVenueUniqueIdentifier());
            vipPlanMapper.addUserRecord(userRecord);
        }
        // 拿到用户的默认身高体重
//        BodyFatModel bodyFatModel = userRecordMapper.selectBodyFat(addPlanModel.getMemberUserId());
//        Double aDouble = bodyFatPercentageUtils.bodyFatPercentageCalculation(addPlanModel.getUserWeight(), bodyFatModel.getMemberUserHeight(), bodyFatModel.getMemberUserAge(), bodyFatModel.getMemberUserSex());
    }
    @Override
    public CommonResult getSelectYear(Integer id, String venueUniqueIdentifier) {
        LinkedHashSet<String> yearSet = new LinkedHashSet<>();
        QueryWrapper<Reservation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("coach_id",id);
        queryWrapper.orderByDesc("update_time");
//        queryWrapper.eq("venue_unique_identifier",venueUniqueIdentifier);
        List<Reservation> reservationList = reservationMapper.selectList(queryWrapper);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");
        for(Reservation reservation : reservationList){
            Date updateTime = reservation.getUpdateTime();
            String yearMonth = dateFormat.format(updateTime);
            yearSet.add(yearMonth);
        }
        String[] yearArry = yearSet.toArray(new String[0]);
        return  CommonResult.ok(yearArry);
    }

    /**
     * @Author wx 查询约课状态
     * @Description
     * @Date 2023/12/14 11:30
     * @Return
     * @param studentId
     */
    @Override
    public CommonResult selectResStatus(Integer courseId, Integer studentId, Integer coachId) {
        return CommonResult.ok(reservationMapper.selectResStatus(courseId,studentId,coachId));
    }

    @Override
    public CommonResult getCount(List<Date> daiXunLianDate,String invitationCode,Integer coachId) {
        CountModel time = vipPlanMapper.getTime(coachId);
        List<CountModel> list = new ArrayList<>();
        List<CountModel> lists = new ArrayList<>();
        for (int i = 0; i < daiXunLianDate.size(); i++) {
            Date date = daiXunLianDate.get(i);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = sdf.format(date);
            CountModel count = vipPlanMapper.getCount(formattedDate, invitationCode);
            lists.add(count);
        }
        for (int j = 0; j < lists.size(); j++) {
            Integer courseSize = lists.get(j).getCourseSize();
            CountModel countModel = new CountModel();
            countModel.setCourseSize(courseSize);
            countModel.setTimeSize(time.getTimeSize());
            list.add(countModel);
        }
        return CommonResult.ok(list);
    }
}
